<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/10/27
 * Time: 00:02
 */

namespace app\article\controller;

use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ThirdApp;
use app\common\cachemodel\ZlGoddessState;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use app\common\model\Article;
use app\common\model\Article as ArticleModel;
use app\common\model\PushServer;
use app\common\model\Slide;
use think\Controller;
use think\Env;
use think\Exception;

/**
 * 文章相关页面
 * Class Web
 * @package app\article\controller
 */
class Web extends Controller
{
    protected $colors = [
        0 => ['name' => '困难', 'color' => '#7775ff',],
        1 => ['name' => '警戒', 'color' => '#ffa536',],
        2 => ['name' => '平平', 'color' => '#ffed17',],
        3 => ['name' => '吉利', 'color' => '#00f4e7',],
        4 => ['name' => '大吉', 'color' => '#00e9a0',],
    ];

    private $LOG_PRE = '女神动态视频分享web错误：';

    private $oss = '';
    private $domain = '';
    private $share_img = '';
    protected $signImg = [
        'https://oss.goddessxzns.com/web/week_fortune/sign-1.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-2.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-3.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-4.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-5.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-6.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-7.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-8.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-9.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-10.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-11.png',
        'https://oss.goddessxzns.com/web/week_fortune/sign-12.png',
    ];
    protected $signName = [
        '白羊座',
        '金牛座',
        '双子座',
        '巨蟹座',
        '狮子座',
        '处女座',
        '天秤座',
        '天蝎座',
        '射手座',
        '摩羯座',
        '水瓶座',
        '双鱼座',
    ];
    /**
     * @var Jssdk
     */
    protected $JSSDK;

    public function _initialize()
    {
        $this->JSSDK = new Jssdk();
        $this->oss = Env::get('host.photo');
        $this->domain = $this->oss;
        $this->share_img = $this->domain . '/static/video_share/images/share_logo.png';

        $param = $this->request->param();
        $app_type = $param['app-type'] ?? 'web';
        $version = $param['version'] ?? '';
        $this->assign(['app_type' => $app_type, 'version' => $version]);
        $this->assign('oss', Env::get('host.photo'));
        $this->assign('domain', Env::get('host.domain'));
    }

    /**
     * 查看文章详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function details()
    {
        $id = input('param.id/d', 0);
        $type = input('param.type/d', 1);
        if (!$id)
        {
            return show(config('code.error'), '缺少id');
        }
        try
        {
            $configModel = new ConfigManage();

            if ($type === 1)
            {   // 星文
                $data = (new Article())->getArticleDetails(null, ['id' => $id, 'is_old' => true], 0);
                $data['user_type'] = $configModel->innerUser((int)($data['a_id'] ?? 0));
            } else
            {
                // 女神动态
                $stateInfo = (new ZlGoddessState())->getInfoById($id, ['type', 'url', 'thumb', 'title', 'publish_time', 'author', 'avatar', 'content', 'introduction', 'comment_num', 'good_num', 'collect_num', 'duration', 'read_num', 'read_base', 'a_id']);
                if (!$stateInfo)
                {
                    return show(config('code.error'), '动态不存在');
                }
                if ($stateInfo['type'] == 1)
                {
                    $data = [
                        'id' => $id,
                        'title' => $stateInfo['title'],
                        'introduction' => $stateInfo['introduction'],
                        'content' => $stateInfo['content'],
                        'author' => $stateInfo['author'],
                        'avatar' => $stateInfo['avatar'],
                        'thumb' => $stateInfo['thumb'],
                        'publish_time' => $stateInfo['publish_time'],
                        'good' => $stateInfo['good_num'] < 0 ? 0 : $stateInfo['good_num'],
                        'collect' => $stateInfo['collect_num'] < 0 ? 0 : $stateInfo['collect_num'],
                        'read' => $stateInfo['read_num'],
                        'user_type' => $configModel->innerUser((int)($stateInfo['a_id'] ?? 0))
                    ];
                } else
                {
                    $goodNum = (int)(($stateInfo['good_num'] ?? 0) + floor(((($stateInfo['read_num'] ?? 0) + ($stateInfo['read_base'] ?? 0)) / 30)));
                    $resData['article_info'] = [
                        'id' => $id,
                        'type' => (int)($stateInfo['type'] ?? 0),
                        'url' => $stateInfo['url'] ?? '',
                        'thumb' => $stateInfo['thumb'] ?? '',
                        'title' => $stateInfo['title'] ?? '',
                        'time' => Util::timeToStr($stateInfo['publish_time']) ?? '',
                        'author' => $stateInfo['author'] ?? '',
                        'avatar' => $stateInfo['avatar'] ?? '',
                        'content' => htmlspecialchars_decode($stateInfo['content'] ?? ''),
                        'introduction' => $stateInfo['introduction'] ?? '',
                        'comment_num' => (int)($stateInfo['comment_num'] ?? 0),
                        'good_num' => $goodNum < 0 ? 0 : $goodNum,
                        'collect_num' => ($stateInfo['collect_num'] ?? 0) < 0 ? 0 : (int)($stateInfo['collect_num'] ?? 0),
                        'duration' => (int)($stateInfo['duration'] ?? 0),
                        'user_type' => $configModel->innerUser((int)($stateInfo['a_id'] ?? 0))
                    ];

                    $data = (new ArticleComment())->getPageCommentList('', 2, $id, 2, 1, 3);
                    $data = array_merge($resData, $data);
                    $signPackage = $this->JSSDK->getSignPackage();

                    return $this->fetch('video_share', [
                        'title' => $resData['article_info']['title'],//网页标题
                        'share_title' => $resData['article_info']['title'],//微信分享标题
                        'share_introduction' => $resData['article_info']['introduction'],//微信分享内容
                        'share_img' => $this->share_img,
                        'signPackage' => $signPackage,//微信签名
                        'data' => $data,//带过去的数据
                        'oss' => $this->oss,
                        'domain' => $this->domain
                    ]);
                }
            }

            $signPackage = $this->JSSDK->getSignPackage();

            return $this->fetch('index', [
                'signPackage' => $signPackage,
                'data' => $data,
                'oss' => $this->oss,
                'type' => $type, // 1文章 2动态
            ]);
        }
        catch (Exception $e)
        {
            throw new Exception('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . $this->LOG_PRE . 'id=' . $id . $e->getMessage());
        }
    }
    // 轮播图图文跳转二次分享

    /**
     * 查看文章详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function details2()
    {
        $id = input('param.id/d', 0);
        $type = input('param.type/d', 1);
        if (!$id)
        {
            throw new ApiException('服务异常，数据不存在');
        }
        try
        {
            $configModel = new ConfigManage();
            if ($type === 1)
            {   // 星文
                $data = (new Article())->getArticleDetails(null, ['id' => $id, 'is_old' => true], 0);
                $data['user_type'] = $configModel->innerUser((int)($data['a_id'] ?? 0));
            } else
            {
                // 女神动态
                $stateInfo = (new ZlGoddessState())->getInfoById($id, ['type', 'url', 'thumb', 'title', 'publish_time', 'author', 'avatar', 'content', 'introduction', 'comment_num', 'good_num', 'collect_num', 'duration', 'read_num', 'read_base', 'a_id']);
                if (!$stateInfo)
                {
                    throw new ApiException('服务异常，数据不存在');
                }
                if ($stateInfo['type'] == 1)
                {
                    $data = [
                        'id' => $id,
                        'title' => $stateInfo['title'],
                        'introduction' => $stateInfo['introduction'],
                        'content' => $stateInfo['content'],
                        'author' => $stateInfo['author'],
                        'avatar' => $stateInfo['avatar'],
                        'thumb' => $stateInfo['thumb'],
                        'publish_time' => $stateInfo['publish_time'],
                        'good' => $stateInfo['good_num'] < 0 ? 0 : $stateInfo['good_num'],
                        'collect' => $stateInfo['collect_num'] < 0 ? 0 : $stateInfo['collect_num'],
                        'read' => $stateInfo['read_num'],
                        'user_type' => $configModel->innerUser((int)($stateInfo['a_id'] ?? 0))
                    ];
                } else
                {
                    throw new ApiException('服务异常，数据不存在');
                }
            }

            return $this->fetch('index2', [
                'data' => $data,
                'oss' => $this->oss,
                'type' => $type, // 1文章 2动态
            ]);
        }
        catch (Exception $e)
        {
            throw new Exception('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . $this->LOG_PRE . 'id=' . $id . $e->getMessage());
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \app\common\lib\exception\ApiException
     */
    public function share_details()
    {
        $id = input('param.id/d', 0);
        $type = input('param.type/d', 1);//1=>获取轮播图信息（cid=>1），2=>获取启动页信息(cid=>2),3=>获取banner公告信息(cid=3),5=>问答banner
        if (!in_array($type, [1, 2, 3, 5], false))
        {
            $data = [];
        } else
        {
            $data = (new Slide())->getWebSlideInfo($type, $id);
        }
        if ($data)
        {
            $isXzns = (new Util())->isCmopanyIp();
            if ($isXzns === false && $data['status'] != 1)
            {
                $data = [];
            }
        }
        if (!$id || !$data) exit('内容不存在！');

        $signPackage = $this->JSSDK->getSignPackage();

        $aData = [];
        $mLinkConfig = [];
        if ($this->request->has('zhunleshare'))
        {
            $reg1 = "/<a .*?>.*?<\/a>/";
            $mHost = Env::get('host.m');
            $mHostLen = strlen($mHost);
            preg_match_all($reg1, $data['content'], $aData);
            $reg2 = "/href=[\"\\']([^\"\\']+)/";
            foreach ($aData[0] as $k => $v)
            {
                preg_match($reg2, $v, $param);
                $start = strpos($param[1], $mHost);
                if ($start !== false)
                {
                    $par = trim(substr($param[1], $start + $mHostLen), '/');

                    $parArr = explode('?', $par);

                    if (in_array($parArr[0], ['third_app', 'jump_mobile_browser'], true))
                    {
                        if ($parArr[0] === 'third_app')
                        {
                            parse_str(htmlspecialchars_decode($parArr[1]), $paramArr);

                            $thirdData = (new ThirdApp())->getThirdInfoFromCache($paramArr['id']);

                            $urlHref = $thirdData['third_href'] ?? '';
                        } else
                        {
                            parse_str(htmlspecialchars_decode($parArr[1]), $paramArr);

                            $urlHref = $paramArr['link'] ?? '';
                        }

                        $str = str_replace($param[0], 'href="' . $urlHref . '"', $v);

                        $data['content'] = str_replace($v, $str, $data['content']);
                    } else
                    {
                        $mlink = '';

                        if (count($parArr) > 1)
                        {
                            $mlink = $par;
                        }

                        $str = str_replace($param[0], 'href="javascript:;" class="btn' . $k . '"', $v);

                        $data['content'] = str_replace($v, $str, $data['content']);

                        $mLinkConfig[$k] = $mlink;
                    }
                }
            }
        }

        return $this->fetch('share_index', ['signPackage' => $signPackage, 'data' => $data, 'mLinkConfig' => $mLinkConfig]);
    }
    // 推送图文跳转二次分享

    /**
     * @param $id
     * @return mixed
     * @throws \app\common\lib\exception\ApiException
     */
    public function push_details($id)
    {
        $data = (new PushServer())->getPushServer(['id' => $id]);

        if (!$id || !$data) exit('文章不存在！');

        $signPackage = $this->JSSDK->getSignPackage();

        return $this->fetch('push_index', ['signPackage' => $signPackage, 'data' => $data]);
    }


    /**
     * 获取周运文章
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function fortune_detail()
    {
        $in_sign = input('in_sign/d', 1);
        if (!in_array($in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            return show(0, '星座未知');
        }

        $day = (new ArticleModel())->getFortune('day', $in_sign);
        $day['time_range'] = date('Y.m.d', strtotime($day['publish_time'])) . '-' . date('Y.m.d', strtotime($day['publish_time'] . ' +6 day'));
        $week = (new ArticleModel())->getFortune('week', $in_sign);
        $week['time_range'] = date('Y.m.d', strtotime($week['publish_time'])) . '-' . date('Y.m.d', strtotime($week['publish_time'] . ' +6 day'));
        $month = (new ArticleModel())->getFortune('month', $in_sign);
        $month['time_range'] = date('Y.m.01', strtotime($month['publish_time'])) . '-' . date('m.d', strtotime($month['publish_time'] . ' +1 month -1 day'));
        $year = (new ArticleModel())->getFortune('year', $in_sign);
        $year['time_range'] = date('Y.01.01', strtotime($year['publish_time'])) . '-12.31';

        $fortuneData = [
            'fortune_day' => $day,
            'fortune_week' => $week,
            'fortune_month' => $month,
            'fortune_year' => $year
        ];
        $resData = [
            'luck_adversity' => $this->colors,
        ];
        foreach ($fortuneData as $key => $fortuneItem)
        {
            $scoreData = [
                [
                    'name' => '整体',
                    'score' => $fortuneItem['whole'] ?? 0,
                ],
                [
                    'name' => '感情',
                    'score' => $fortuneItem['love'] ?? 0,
                ],
                [
                    'name' => '财富',
                    'score' => $fortuneItem['money'] ?? 0,
                ],
                [
                    'name' => '事业',
                    'score' => $fortuneItem['career'] ?? 0,
                ],
                [
                    'name' => '健康',
                    'score' => $fortuneItem['health'] ?? 0,
                ]
            ];
            $scoreList = [];
            foreach ($scoreData as $datum)
            {
                $resScore = Util::getScorePercentInfo2($datum['score']);
                $resScore['name'] = $datum['name'];
                $scoreList[] = $resScore;
            }


            $resData[$key] = [
                'title' => $fortuneItem['introduction'],
                'introduction' => $fortuneItem['time_range'],
                'content' => $fortuneItem['content'],
                'score_list' => $scoreList,
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 周运文章分享页
     * @return mixed
     * @throws \app\common\lib\exception\ApiException
     */
    public function week_share_details()
    {
        $date = Util::getWeekDateALL(time());
        $start_day = reset($date);
        $end_day = end($date);
        [$start_year, $start_month, $start_day] = explode('-', $start_day);
        [$end_year, $end_month, $end_day] = explode('-', $end_day);
        $timeInfo = $start_year . '.' . $start_month . '.' . $start_day . ' - ' . $end_month . '.' . $end_day;


        $days = Util::getMonthDays($start_year . '/' . $end_month);// 本月一共有几天
        $timeInfo2 = $start_year . '.' . $start_month . '.01' . ' - ' . $end_month . '.' . $days;
        $timeInfo3 = $start_year . '.01.01' . ' - 12.31';
        $type = input('type/d', 1);
        $in_sign = input('in_sign/d', 1);
        $version = input('version/s', '');
        if (!$in_sign)
        {
            // 异常抛出
            return $this->fetch(ROOT_PATH . 'error.html');
//            throw new Exception('请求异常',404);
        }
        $data = ['timeInfo' => $timeInfo, 'timeInfo2' => $timeInfo2, 'timeInfo3' => $timeInfo3, 'type' => $type, 'sign_img' => $this->signImg, 'sign_name' => $this->signName, 'sign_img_encode' => json_encode($this->signImg, true), 'sign_name_encode' => json_encode($this->signName, true), 'sign_id' => $in_sign, 'colors' => json_encode($this->colors, true)];
        $signPackage = $this->JSSDK->getSignPackage();
//        if (Util::CheckAppVersion('2.9.3', $version) !== '小')
        if ($version)
        {
            $html = 'week_share_index2';
        } else
        {
            $html = 'week_share_index';
        }
        return $this->fetch($html, ['signPackage' => $signPackage, 'data' => $data, 'version' => $version]);
    }
}
